from django import forms
from  web.forms.bootstrap import BootStrapForm
from web import models
from django.core.exceptions import ValidationError

class ProjectModelForm(BootStrapForm,forms.ModelForm):
    bootstrap_class_exclude = ['color']
    class Meta:
        model = models.Project
        fields = ['name','color','desc']
        widgets = {
            'desc': forms.Textarea,
            'color': forms.RadioSelect(attrs={'class':'color-radio'})
        }
    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request

    def clean_name(self):
        """项目检验"""
        name = self.cleaned_data['name']
        #1. 当前用户是否已创建过此项目（项目名是否已存在）
        exists = models.Project.objects.filter(name=name,creator=self.request.trace.user).exists()
        if exists:
            raise ValidationError('项目名已存在')

        count = models.Project.objects.filter(creator=self.request.trace.user).count()
        if count >= self.request.trace.price_police.project.count():
            raise ValidationError('项目个数超限，请购买套餐')
